package com.ssy.lingxi.purchase.serviceimpl.notice;

import cn.hutool.core.collection.CollectionUtil;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.ssy.lingxi.common.constant.basic.EnableDisableStatus;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.common.utils.CollectionPageUtil;
import com.ssy.lingxi.purchase.api.dto.request.CommonIdRequest;
import com.ssy.lingxi.purchase.api.dto.request.PurchaseNoticeListRequest;
import com.ssy.lingxi.purchase.api.dto.response.PurchaseNoticeResponse;
import com.ssy.lingxi.purchase.api.dto.response.WinTenderAnnounceFileResponse;
import com.ssy.lingxi.purchase.api.enums.notice.PurchaseNoticeTypeEnum;
import com.ssy.lingxi.purchase.entity.bidding.QBidding;
import com.ssy.lingxi.purchase.entity.notice.PurchaseNotice;
import com.ssy.lingxi.purchase.entity.notice.QPurchaseNotice;
import com.ssy.lingxi.purchase.entity.purchaseinquiry.QPurchaseInquiry;
import com.ssy.lingxi.purchase.entity.tender.InviteTender;
import com.ssy.lingxi.purchase.entity.tender.QInviteTender;
import com.ssy.lingxi.purchase.entity.tender.WinTenderAnnounceFile;
import com.ssy.lingxi.purchase.repository.notice.PurchaseNoticeRepository;
import com.ssy.lingxi.purchase.repository.tender.InviteTenderRepository;
import com.ssy.lingxi.purchase.service.notice.PurchaseNoticeService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 企业直采 - 采购公示 - 业务实现类
 * @author fhj
 * @date 2021/05/26
 * @version 2.0.0
 * */
@Slf4j
@Service
public class PurchaseNoticeServiceImpl implements PurchaseNoticeService {

    @Resource
    private PurchaseNoticeRepository purchaseNoticeRepository;
    @Resource
    private InviteTenderRepository inviteTenderRepository;
    @Resource
    private JPAQueryFactory jpaQueryFactory;

    @Override
    @ApiOperation(value = "列表")
    public Wrapper<PageData<PurchaseNoticeResponse>> list(PurchaseNoticeListRequest qo, UserLoginCacheDTO user, Long shopId) {
        //查询表实体 - 采购公示
        QPurchaseNotice purchaseNotice = QPurchaseNotice.purchaseNotice;
        BooleanBuilder predicates = new BooleanBuilder();
        if(qo.getType() != null) {
            predicates.and(purchaseNotice.type.eq(qo.getType()));
        }
        if(StringUtils.isNotBlank(qo.getName())) {
            predicates.and(purchaseNotice.name.like("%" + qo.getName() + "%"));
        }
        if(qo.getMemberId() != null) {
            predicates.and(purchaseNotice.memberId.eq(qo.getMemberId()));
        }
        if(qo.getRoleId() != null) {
            predicates.and(purchaseNotice.roleId.eq(qo.getRoleId()));
        }
        if(qo.getStartTime() != null) {
            predicates.and(purchaseNotice.createTime.goe(qo.getStartTime()));
        }
        if(qo.getEndTime() != null) {
            predicates.and(purchaseNotice.createTime.loe(qo.getEndTime()));
        }
        //查询
        JPAQuery<PurchaseNotice> query = jpaQueryFactory.select(purchaseNotice).from(purchaseNotice).where(predicates);
        List<PurchaseNotice> list = query.orderBy(purchaseNotice.createTime.desc()).fetch();

        list = list.stream().filter(notice -> !CollectionUtils.isEmpty(notice.getShopIds()) && notice.getShopIds().contains(shopId)).collect(Collectors.toList());

        //条件:是否与当前会员相关
        if(user != null && qo.getAboutUs() != null && qo.getAboutUs().equals(EnableDisableStatus.ENABLE.getCode())) {
            list = list.stream().filter(a -> a.getMemberIds().contains(user.getMemberId())).collect(Collectors.toList());
        }

        //校验
        if(CollectionUtil.isEmpty(list)) {
            return Wrapper.success(new PageData<>(0L , new ArrayList<>()));
        }

        //总记录数
        Long totalCount = (long) list.size();

        //获取分页数据
        list = CollectionPageUtil.pageList(list, qo.getCurrent(), qo.getPageSize());
        List<PurchaseNoticeResponse> collect = list.stream().map(a -> {
            PurchaseNoticeResponse purchaseNoticeResponse = new PurchaseNoticeResponse();
            BeanUtils.copyProperties(a, purchaseNoticeResponse);
            return purchaseNoticeResponse;
        }).collect(Collectors.toList());

        return Wrapper.success(new PageData<>(totalCount , collect));
    }

    @Override
    @ApiOperation(value = "详情")
    public Wrapper<PurchaseNoticeResponse> details(CommonIdRequest dto) {
        PurchaseNotice purchaseNotice = purchaseNoticeRepository.findById(dto.getId()).orElse(null);
        if(purchaseNotice != null) {
            PurchaseNoticeResponse purchaseNoticeResponse = new PurchaseNoticeResponse();
            BeanUtils.copyProperties(purchaseNotice, purchaseNoticeResponse);

            //封装公示相关的附件(目前只有招标有附件)
            if(purchaseNotice.getDataId() != null) {
                if(purchaseNotice.getType().equals(PurchaseNoticeTypeEnum.INVITE_TENDER.getCode())) {
                    InviteTender inviteTender = inviteTenderRepository.findById(purchaseNotice.getDataId()).orElse(null);
                    if(inviteTender != null) {
                        List<WinTenderAnnounceFile> winTenderAnnounceFile = inviteTender.getWinTenderAnnounceFile();
                        if(CollectionUtil.isNotEmpty(winTenderAnnounceFile)) {
                            purchaseNoticeResponse.setWinTenderAnnounceFile(
                                    winTenderAnnounceFile.stream().map(a -> {
                                        WinTenderAnnounceFileResponse response = new WinTenderAnnounceFileResponse();
                                        BeanUtils.copyProperties(a, response);
                                        return response;
                                    }).collect(Collectors.toList())
                            );
                        }
                    }
                }
            }
            return Wrapper.success(purchaseNoticeResponse);
        }

        return Wrapper.fail("根据ID找不到采购公示");
    }
}
